/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.gu.derp.http;

import edu.gu.derp.model.Account;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author jakob
 */
@WebFilter(filterName = "AuthFilter", urlPatterns = {"/*"})
public class AuthFilter implements Filter {
    public AuthFilter() {
    }

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        
        String loginURL = "/login.jsf";
        String registerURL = "/register.jsf";
        String requestURI = request.getRequestURI();
        if (account == null && 
            !requestURI.equals(loginURL) &&
            !requestURI.equals(registerURL) &&
            !requestURI.endsWith(".jpg") &&
            !requestURI.endsWith(".png") &&
            !requestURI.endsWith(".png.jsf") &&
            !requestURI.endsWith(".css") &&
            !requestURI.endsWith(".css.jsf")) {
            response.sendRedirect(loginURL);
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
